<template>
	<view class="bg-white" style="height: 100vh;">
		<cu-custom :isBack="true" leftIcon="delete" :showLeftIcon="false" @leftBtnClick="deleteDraftAction">
			<block slot="backText">返回</block>
			<block slot="content">发布动态</block>
		</cu-custom>
		<scroll-view scroll-y class="bg-white">
			<view class="padding">
				<textarea maxlength="-1" v-model="content" placeholder="分享此刻的想法..."
					style="height: 360upx;font-size: 36upx;"></textarea>
			</view>
			<view v-if="imgList.length>0" class="padding-left padding-right">
				<view v-for="(subImgList,index) in showImageList" :key="index">
					<view class="grid col-4 grid-square flex-sub" style="width: 100%;">
						<view class="bg-img" v-for="(subItem,imgIndex) in subImgList" :key="imgIndex"
							@click="ViewImage" :data-url="subItem.local" :data-listIndex="index">
							<image
								:class="(subItem.is_uping==false&&subItem.remote==null)||(subItem.is_uping==true)?'bg-mask':''"
								:src="subItem.local" mode="aspectFill"></image>
							<view class="cu-load load-cuIcon text-white padding-top"
								:class="subItem.is_uping?'loading':'over'"></view>
							<view class="cu-tag bg-red" @tap.stop="DelImg" :data-listIndex="index"
								:data-index="imgIndex">
								<text class='cuIcon-close'></text>
							</view>
							<view v-if="subItem.is_uping==false&&subItem.remote==null">
								<view @click.stop="retryUpload(subItem,imgIndex,index)"
									style="position: absolute;z-index: 2;top: 40upx;right: 25upx;">
									<view class="flex justify-center align-center" style="flex-direction: column;">
										<text class="text-white sm">上传失败</text>
										<text class="text-white sm">点击重试</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="videoPath&&videoPath.length>0" class="flex justify-start align-center padding-left padding-top">
				<video :show-fullscreen-btn="true" :enable-play-gesture="false" :show-center-play-btn="true"
					:controls="false" :src="videoPath" objectFit="cover" style="width: 150upx;height: 150upx;"></video>
				<view class="cu-tag bg-red close-badge" @tap.stop="DelVideo">
					<text class='cuIcon-close'></text>
				</view>
				<view class="flex justify-start align-center">
					<view class="padding-left cu-load load-cuIcon" :class="requestStatus.isUpingVideo?'loading':'over'">
					</view>
					<view v-if="requestStatus.isUpingVideo">
						<text class="padding-left-xs text-grey text-sm">上传中</text>
					</view>
					<view v-if="videoPath.length>0&&requestStatus.isUpingVideo==false">
						<text
							class="padding-left-xs text-grey text-sm">{{requestStatus.upingVideoSuccess?'上传成功':'上传失败'}}</text>
					</view>
				</view>
			</view>
			<view class="flex justify-start align-center">
				<view v-if="audioPath&&audioPath.length>0" class="text-xl text-bold text-gray padding-left padding-right">
					<text @tap="deleteAudio" class="cuIcon-delete"></text>
				</view>
				<view class="padding" style="width: 80%;">
					<audio-player @onGetDuration="onGetAudioDuration" :autoplay="true" v-if="audioPath!==null"
						:src="audioPath"></audio-player>
				</view>
				<view class="flex justify-start align-center">
					<view class="padding-left cu-load load-cuIcon"
						:class="requestStatus.isAudioUploading?'loading':'over'"></view>
					<view v-if="requestStatus.isAudioUploading">
						<text class="padding-left-xs text-grey text-sm">上传中</text>
					</view>
					<view v-if="audioPath.length>0&&requestStatus.isAudioUploading==false">
						<text
							class="padding-left-xs text-grey text-sm">{{requestStatus.isAudioUploadSuccess?'上传成功':'上传失败'}}</text>
					</view>
				</view>
			</view>
			<view class="flex justify-between align-center text-xl padding-bottom">
				<button @tap="showEmojiPanel=!showEmojiPanel" class="cuIcon-emoji radius"></button>
				<button :disabled="imgList.length>=9?true:false" @tap="ChooseImage" class="cuIcon-pic radius bg-gray"></button>
				<button v-if="isManager" :disabled="audioPath.length>0" @tap="chooseVideo" class="cuIcon-record radius bg-gray"></button>
				<button v-if="enableAudioContent==1" :disabled="videoPath.length>0" @tap="showAudioRecord" class="cuIcon-voice radius bg-gray"></button>
			</view>
			<view v-if="circleId!==null" @tap="chooseTopic" class="flex justify-between align-center padding solid-bottom"
				style="width: 100%;">
				<text class="text-lg">选择圈话题</text>
				<view class="flex justify-end align-center">
					<view v-if="topic&&topic.length>0" class="flex justify-start align-center padding-right">
						<view class="cu-tag line-blue radius">#{{topic}}</view>
						<text @tap.stop="clearTopic" class="cuIcon-close text-gray padding-left-sm"></text>
					</view>
					<text class="cuIcon-right text-grey"></text>
				</view>
			</view>
			<view v-if="fromIndex" @tap="chooseCircle" class="flex justify-between align-center padding solid-bottom"
				style="width: 100%;">
				<text class="text-lg">选择圈子</text>
				<view class="flex justify-end align-center">
					<view v-if="circle!==null" class="flex justify-start align-center padding-right">
						<view class="cu-tag line-blue radius">{{circle.name}}</view>
					</view>
					<text class="cuIcon-right text-grey"></text>
				</view>
			</view>
			<view v-if="showEmojiPanel" class="padding-left-sm padding-right-sm padding-bottom">
				<emotion @emotion="handleEmotion" :height="350"></emotion>
			</view>
		</scroll-view>
		<view class="cu-tabbar-height"></view>
		<view class="cu-bar tabbar bg-white foot action flex justify-around align-center padding-top"
			style="width: 100%;">
			<button @tap="commitAction()" :class="'cu-btn round '+themeColor" style="width: 65%;">发表</button>
		</view>
		<view @tap="clickAudioRecordMask" v-if="showAudioPanel"
			style="width: 100vh;height: 100vh;background-color: rgba(0,0,0,0.1);z-index: 99999;position: absolute;top: 1upx;">
		</view>
		<audio-record @save="finishRecordAudio" @onHidden="showAudioPanel=false" @onShow="showAudioPanel=true"
			ref="audioRecord" class="audio-recorder"></audio-record>
	</view>
</template>

<script>
	import Emotion from '@/components/Emotion/index.vue'
	import AudioRecord from '@/components/audio-record.vue'
	import AudioPlayer from '@/components/audio-player.vue'
	import {
		createPost,
		uploadFile,
		uploadImage,
		getMyCircleList
	} from '@/api/api.js'
	import {
		chunk
	} from '@/api/utils.js'
	import {
		getUserInfo
	} from '@/api/auth.js'
	import config from '@/api/config.js'
	export default {
		components: {
			Emotion,
			AudioRecord,
			AudioPlayer
		},
		computed: {
			isManager() {
				if (this.appSetting.enable_user_video == 1) {
					return true
				}
				let userInfo = getUserInfo()
				if (userInfo.role == null) {
					return false
				}
				//是不是认证用户
				if (userInfo.group && userInfo.group.open_choose == 0) {
					return true
				}
				return userInfo.role_id > 0
			},
			showImageList() {
				let showList = chunk(this.imgList,4)
				return showList
			}
		},
		data() {
			return {
				appSetting: this.AppSetting,
				enableAudioContent:config.enableAudioContent,
				circle:null,
				fromIndex:false,
				topic: null,
				topicId: null,
				showAudioPanel: false,
				circleId: null,
				themeColor: this.ThemeColor,
				showEmojiPanel: false,
				audioPath: null,
				audioDuration: 0,
				audioRemote: null,
				content: '',
				imgList: [],
				videoPath: null,
				videoRemote: null,
				requestStatus: {
					isAudioChoosed: false,
					isAudioUploading: false,
					isAudioUploadSuccess: false,
					isUpingVideo: false,
					upingVideoSuccess: false
				}
			}
		},
		onLoad(options) {
			if (options.circleId !== null && options.circleId !== undefined) {
				this.circleId = options.circleId
			}
			if(options.fromIndex !== null && options.fromIndex !== undefined) {
				this.fromIndex = true
			}
		},
		methods: {
			chooseCircle() 
			{
				let that = this
				uni.navigateTo({
					url:'/pages/lessuse/circle-list/circle-list?mode=choose',
					events: {
						finishChoose:function(res){
							console.log(res)
							that.circleId = res.circle_id
							that.circle = res
						}
					}
				})
			},
			deleteAudio() 
			{
				this.audioPath = null 
				this.audioRemote = null
			},
			randomString(e) {
				e = e || 32
				var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
				let a = t.length
				let n = "";
				for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
				return n
			},
			ChooseImage(index) {
				if(this.imgList.length>=9) {
					uni.showToast({
						icon:'none',
						title:'最多选择9张图片'
					})
					return
				}
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						for (let index = 0; index < res.tempFilePaths.length; index++) {
							let timestamp = new Date().getTime()
							let fileKey = String(timestamp)
							let random = this.randomString(6)
							fileKey += random
							let item = {
								'local': res.tempFilePaths[index],
								'remote': null,
								'is_uping': false,
								'fileKey': fileKey,
							}
							this.imgList.push(item)
						}
						this.imgList.forEach(item => {
							if (item.is_uping == false && item.remote == null) {
								item.is_uping = true
								uploadImage(item.local, item.fileKey, (imgUrl) => {
									console.log(imgUrl)
									item.remote = imgUrl
									item.is_uping = false
								}, (error) => {
									item.is_uping = false
								})
							} else {
								console.log('file path is uploading:' + item);
							}
						})
					}
				});
			},
			ViewImage(e) {
				let index = e.currentTarget.dataset.listindex
				console.log(e.currentTarget.dataset.url)
				let currentUrl = e.currentTarget.dataset.url
				if (currentUrl == null || currentUrl.length == 0) {
					return
				}
				let previewImgList = []
				this.imgList.forEach(item => {
					previewImgList.push(item.local)
				})
				uni.previewImage({
					urls: previewImgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				console.log(e)
				let index = e.currentTarget.dataset.listindex
				let delIndex = 4 * index + e.currentTarget.dataset.index
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(delIndex, 1)
						}
					}
				})
			},
			retryUpload(item, index, listIndex) {
				this.imgList[index].is_uping = true
				uploadImage(item.local, item.fileKey, (imgUrl) => {
					console.log(imgUrl)
					this.imgList[index].remote = imgUrl
					this.imgList[index].is_uping = false
				}, (error) => {
					this.imgList[index].is_uping = false
				})
			},
			DelVideo() {
				this.videoPath = null
				this.videoRemote = null
			},
			chooseVideo() {
				let that = this
				uni.chooseVideo({
					count: 1,
					maxDuration: 15,
					compressed: false,
					sourceType: ['camera', 'album'],
					success: function(res) {
						that.videoPath = res.tempFilePath;
						//上传视频
						let timestamp = new Date().getTime()
						let fileKey = String(timestamp) + '_' + res.width + '_' + res.height + '.mp4'
						that.requestStatus.isUpingVideo = true
						uploadFile(res.tempFilePath, fileKey, remoteUrl => {
							that.videoRemote = remoteUrl
							that.requestStatus.isUpingVideo = false
							that.requestStatus.upingVideoSuccess = true
						}, error => {
							console.log(error)
							that.requestStatus.isUpingVideo = false
							that.requestStatus.upingVideoSuccess = false
						})
					}
				});
			},
			clearTopic() {
				this.topic = null
				this.topicId = null
			},
			chooseTopic() {
				let self = this
				uni.navigateTo({
					url: '/pages/lessuse/circle-topic/circle-topic?circleId=' + this.circleId,
					events: {
						finishChoose: (data) => {
							if (data['topic'] !== null && data['topic'] !== undefined) {
								self.topic = data['topic']
							}
							if (data['topicId'] !== null && data['topicId'] !== undefined) {
								self.topicId = data['topicId']
							}
						}
					}
				})
			},
			onGetAudioDuration(duration) {
				console.log('get audio duration', duration)
				this.audioDuration = parseInt(duration)
			},
			finishRecordAudio(audioPath) {
				this.requestStatus.isAudioChoosed = true
				console.log(audioPath)
				this.audioPath = audioPath
				//上传语音
				let timestamp = new Date().getTime()
				let fileKey = String(timestamp) + '.mp3'
				uploadFile(this.audioPath, fileKey, remoteUrl => {
					this.audioRemote = remoteUrl
					this.requestStatus.isAudioUploading = false
					this.requestStatus.isAudioUploadSuccess = true
				}, error => {
					console.log(error)
					this.requestStatus.isAudioUploading = false
					this.requestStatus.isAudioUploadSuccess = false
				})
			},
			clickAudioRecordMask() {
				this.$refs.audioRecord.hiddenTabbar()
			},
			showAudioRecord() {
				console.log('tapAudioRecord')
				let that = this
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.record'] == null || res.authSetting['scope.record'] ==
							undefined) {
							uni.authorize({
								scope: 'scope.record',
								success() {
									that.$refs.audioRecord.showTabBar()
								}
							})
						} else {
							if (res.authSetting['scope.record'] == false) {
								uni.openSetting({
									success() {
										console.log('open setting success!')
									}
								})
							} else {
								that.$refs.audioRecord.showTabbar()
							}
						}
					}
				})
			},
			commitAction() {
				if(this.circleId == null) {
					uni.showToast({
						icon:'none',
						title:'请选择需要发布的圈子'
					})
					return
				}
				let richContent = []
				if(this.content&&this.content.length==0&&this.audioRemote==null&&this.videoRemote==null&&this.imgList.length==0) {
					uni.showToast({
						icon:'none',
						title:'文字、图片、视频、语音都没有，无法发布!'
					})
					return
				}
				if(this.content && this.content.length > 500) {
					uni.showToast({
						icon:'none',
						title:'文本长度不能超过500字!'
					})
					return
				}
				if (this.content && this.content.length > 0) {
					let textContent = {
						type: 'text',
						type_name: '文字',
						content: this.content,
						is_bold: false,
						font_size: 14,
						display_font_size: 'lg',
						font_size_name: 'lg',
						text_color: 'black'
					}
					richContent.push(textContent)
				}
				if (this.audioRemote && this.audioRemote.length > 0 && this.audioDuration > 0) {
					let audioContent = {
						type: 'audio',
						type_name: '语音',
						url: this.audioRemote,
						duration: this.audioDuration
					}
					richContent.push(audioContent)
				}

				if (this.videoRemote && this.videoRemote.length > 0) {
					let videoContent = {
						type: 'video',
						type_name: '视频',
						url: this.videoRemote
					}
					richContent.push(videoContent)
				}
				
				if (this.imgList && this.imgList.length > 0) {
					let urlList = []
					this.imgList.forEach(item=>{
						urlList.push(item.remote)
					})
					let gridImgContent = {
						type:'grid_image',
						type_name:'宫格图片',
						url_list:urlList
					}
					richContent.push(gridImgContent)
				}

				let params = {
					'richContent': richContent,
					'circleId': this.circleId
				}
				if (this.topic) {
					params['circleTopic'] = this.topic
				}
				if (this.topicId) {
					params['circleTopicId'] = this.topicId
				}
				uni.showLoading({
					title: '正在发表...'
				})
				createPost(params).then(res => {
					uni.hideLoading()
					uni.$emit('ShowNetworMsg', '发表成功')
					uni.navigateBack({
						delta: 1
					})
				}).catch(error => {
					uni.hideLoading()
				})
			},
			handleEmotion(i) {
				this.content += i
			},
		},
	}
</script>

<style scoped>
	.close-badge {
		position: absolute;
		top: 445upx;
		left: 136upx;
		padding: 0upx 10upx;
	}

	.audio-recorder {
		position: fixed;
		width: 100%;
		bottom: 1upx;
		z-index: 99999;
	}
</style>
